package top.sqdpt.pt.statemachine.factory;

import top.sqdpt.pt.statemachine.action.PtSpringStateAction;
import top.sqdpt.pt.statemachine.machine.PtSpringStateMachine;
import top.sqdpt.pt.statemachine.machine.PtStateMachine;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PtStateMachineFactory {

    private final Map<Enum<?>, PtStateMachine<?, ?>> stateMachineMap = new HashMap<>();

    public PtStateMachineFactory(List<PtSpringStateAction<?, ?, ?>> springStateActions) {

        // 按状态机类型分组动作
        Map<Enum<?>, List<PtSpringStateAction<?, ?, ?>>> actionsByMachine = new HashMap<>();

        for (PtSpringStateAction<?, ?, ?> action : springStateActions) {
            Enum<?> machine = action.getPtStateMachine();
            actionsByMachine.computeIfAbsent(machine, k -> new java.util.ArrayList<>())
                    .add(action);
        }

        // 为每个状态机构建对应的 PtStateMachine
        for (Map.Entry<Enum<?>, List<PtSpringStateAction<?, ?, ?>>> entry : actionsByMachine.entrySet()) {
            Enum<?> machineEnum = entry.getKey();
            List<PtSpringStateAction<?, ?, ?>> actions = entry.getValue();
            PtSpringStateMachine<?, ?, ?> ptSpringStateMachine = new PtSpringStateMachine(machineEnum, actions);
            stateMachineMap.put(machineEnum, ptSpringStateMachine);
        }
    }

    public Map<Enum<?>, PtStateMachine<?, ?>> getStateMachineMap() {
        return Collections.unmodifiableMap(new HashMap<>(this.stateMachineMap));
    }

    public PtStateMachine<?, ?> getStateMachine(Enum<?> stateMachineEnum) {
        return getStateMachineMap().get(stateMachineEnum);
    }
}
